package service

import (
	"fmt"

	"gitee.com/wangshh_123/cross-pay-go/src/models"
	"gorm.io/gorm"
)

// UserCardFeeConfigService 用户卡费配置服务
type UserCardFeeConfigService struct {
	db *gorm.DB
}

// NewUserCardFeeConfigService 创建用户卡费配置服务实例
func NewUserCardFeeConfigService() *UserCardFeeConfigService {
	return &UserCardFeeConfigService{
		db: GetDB(),
	}
}

// CreateUserCardFeeConfig 创建用户卡费配置绑定
func (s *UserCardFeeConfigService) CreateUserCardFeeConfig(req *models.UserCardFeeConfigCreateRequest) (*models.UserCardFeeConfig, error) {
	// 检查用户是否存在
	var user models.User
	if err := s.db.First(&user, req.UserID).Error; err != nil {
		return nil, fmt.Errorf("用户不存在: %v", err)
	}

	// 检查卡费配置是否存在
	var cardFeeConfig models.CardFeeConfig
	if err := s.db.First(&cardFeeConfig, req.CardFeeConfigID).Error; err != nil {
		return nil, fmt.Errorf("卡费配置不存在: %v", err)
	}

	// 检查是否已存在绑定关系
	var existingConfig models.UserCardFeeConfig
	err := s.db.Where("user_id = ? AND card_fee_config_id = ?", req.UserID, req.CardFeeConfigID).
		First(&existingConfig).Error
	if err == nil {
		return nil, fmt.Errorf("该用户已绑定此卡费配置")
	} else if err != gorm.ErrRecordNotFound {
		return nil, fmt.Errorf("查询现有配置失败: %v", err)
	}

	// 创建绑定关系
	config := &models.UserCardFeeConfig{
		UserID:          req.UserID,
		CardFeeConfigID: req.CardFeeConfigID,
		Status:          "active",
	}

	if err := s.db.Create(config).Error; err != nil {
		return nil, fmt.Errorf("创建用户卡费配置绑定失败: %v", err)
	}

	return config, nil
}

// UpdateUserCardFeeConfig 更新用户卡费配置状态
func (s *UserCardFeeConfigService) UpdateUserCardFeeConfig(id int64, req *models.UserCardFeeConfigUpdateRequest) (*models.UserCardFeeConfig, error) {
	var config models.UserCardFeeConfig
	if err := s.db.First(&config, id).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, fmt.Errorf("用户卡费配置不存在")
		}
		return nil, fmt.Errorf("查询用户卡费配置失败: %v", err)
	}

	// 更新状态
	if req.Status != nil {
		config.Status = *req.Status
	}

	if err := s.db.Save(&config).Error; err != nil {
		return nil, fmt.Errorf("更新用户卡费配置失败: %v", err)
	}

	return &config, nil
}

// GetUserCardFeeConfig 获取用户卡费配置
func (s *UserCardFeeConfigService) GetUserCardFeeConfig(id int64) (*models.UserCardFeeConfig, error) {
	var config models.UserCardFeeConfig
	if err := s.db.Preload("User").
		Preload("CardFeeConfig").
		First(&config, id).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, fmt.Errorf("用户卡费配置不存在")
		}
		return nil, fmt.Errorf("查询用户卡费配置失败: %v", err)
	}

	return &config, nil
}

// GetUserCardFeeConfigs 获取用户卡费配置列表
func (s *UserCardFeeConfigService) GetUserCardFeeConfigs(query *models.UserCardFeeConfigQuery) (map[string]interface{}, error) {
	db := s.db.Model(&models.UserCardFeeConfig{}).
		Preload("User").
		Preload("CardFeeConfig")

	// 添加查询条件
	if query.UserID != nil {
		db = db.Where("user_id = ?", *query.UserID)
	}
	if query.CardFeeConfigID != nil {
		db = db.Where("card_fee_config_id = ?", *query.CardFeeConfigID)
	}
	if query.Status != nil {
		db = db.Where("status = ?", *query.Status)
	}

	// 获取总数
	var total int64
	if err := db.Count(&total).Error; err != nil {
		return nil, fmt.Errorf("查询总数失败: %v", err)
	}

	// 分页查询
	var configs []models.UserCardFeeConfig
	offset := (query.Page - 1) * query.PageSize
	if err := db.Offset(offset).Limit(query.PageSize).
		Order("created_at DESC").
		Find(&configs).Error; err != nil {
		return nil, fmt.Errorf("查询用户卡费配置列表失败: %v", err)
	}

	return map[string]interface{}{
		"total":    total,
		"page":     query.Page,
		"pageSize": query.PageSize,
		"list":     configs,
	}, nil
}

// DeleteUserCardFeeConfig 删除用户卡费配置
func (s *UserCardFeeConfigService) DeleteUserCardFeeConfig(id int64) error {
	var config models.UserCardFeeConfig
	if err := s.db.First(&config, id).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return fmt.Errorf("用户卡费配置不存在")
		}
		return fmt.Errorf("查询用户卡费配置失败: %v", err)
	}

	if err := s.db.Delete(&config).Error; err != nil {
		return fmt.Errorf("删除用户卡费配置失败: %v", err)
	}

	return nil
}

// GetUserCardFeeConfigsByUser 获取指定用户的所有卡费配置
func (s *UserCardFeeConfigService) GetUserCardFeeConfigsByUser(userID int64) ([]models.UserCardFeeConfig, error) {
	var configs []models.UserCardFeeConfig

	err := s.db.Preload("CardFeeConfig").
		Where("user_id = ?", userID).
		Order("created_at DESC").
		Find(&configs).Error

	if err != nil {
		return nil, fmt.Errorf("查询用户卡费配置失败: %v", err)
	}

	return configs, nil
}

// GetUserActiveCardFeeConfigs 获取用户激活的卡费配置
func (s *UserCardFeeConfigService) GetUserActiveCardFeeConfigs(userID int64) ([]models.UserCardFeeConfig, error) {
	var configs []models.UserCardFeeConfig

	err := s.db.Preload("CardFeeConfig").
		Where("user_id = ? AND status = 'active'", userID).
		Order("created_at DESC").
		Find(&configs).Error

	if err != nil {
		return nil, fmt.Errorf("查询用户激活的卡费配置失败: %v", err)
	}

	return configs, nil
}

// GetCardFeeConfigs 获取卡费配置列表
func (s *UserCardFeeConfigService) GetCardFeeConfigs(cardType, cardFormFactor, currency, status string, page, pageSize int) (map[string]interface{}, error) {
	db := s.db.Model(&models.CardFeeConfig{})

	// 添加查询条件
	if cardType != "" {
		db = db.Where("card_type = ?", cardType)
	}
	if cardFormFactor != "" {
		db = db.Where("card_form_factor = ?", cardFormFactor)
	}
	if currency != "" {
		db = db.Where("currency = ?", currency)
	}
	if status != "" {
		db = db.Where("status = ?", status)
	}

	// 获取总数
	var total int64
	if err := db.Count(&total).Error; err != nil {
		return nil, fmt.Errorf("查询总数失败: %v", err)
	}

	// 分页查询
	var configs []models.CardFeeConfig
	offset := (page - 1) * pageSize
	if err := db.Offset(offset).Limit(pageSize).
		Order("created_at DESC").
		Find(&configs).Error; err != nil {
		return nil, fmt.Errorf("查询卡费配置列表失败: %v", err)
	}

	return map[string]interface{}{
		"total":    total,
		"page":     page,
		"pageSize": pageSize,
		"list":     configs,
	}, nil
}
